/**
 *
 */
public class Leetcode918 {
    public static void main(String[] args) {
        System.out.println(maxSubarraySumCircular(new int[]{-2, -3, -1}));
    }

    public static int maxSubarraySumCircular(int[] nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }

        int maxSubArray = maxSubArray(nums);

        return maxSubArray < 0 ? maxSubArray : Math.max(maxSubArray, total - minSubArray(nums));
    }


    public static int maxSubArray(int[] nums) {
        int max = Integer.MIN_VALUE;
        int count = 0;
        for (int num : nums) {
            count += num;
            max = Math.max(count, max);

            if (count < 0) {
                count = 0;
            }
        }

        return max;
    }

    public static int minSubArray(int[] nums) {
        int min = Integer.MAX_VALUE;
        int count = 0;
        for (int num : nums) {
            count += num;
            min = Math.min(count, min);

            if (count > 0) {
                count = 0;
            }
        }

        return min;
    }

}

